package show.me.the.money.config.schema;



import java.io.File;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import show.me.the.money.config.ConfigController;
import show.me.the.money.config.MultiConfigController;
import show.me.the.money.util.xml.XMLHelper;



public class SchemaController extends MultiConfigController{
	private static Log logger = LogFactory.getLog(SchemaController.class);
	private static SchemaController sc;
	private SchemaController(){
		CATALOG = ConfigController.CATA_SCHEMA;;
	}
	
	public static SchemaController instance(){
		if(sc == null){
			sc = new SchemaController();
		}
		return sc;
	}
	
	public Schema getSchema(String id){
		Schema schema = (Schema)cache.get(id);
		if(schema == null){
			Document doc = getConfigDoc(id);
			if(doc != null){
				schema = new Schema();
				schema.setDefineDoc(doc);
				cache.put(id, schema);
			}
			else{
				logger.fatal("schema id[" + id + "] not found.");
			}
		}
		return schema;
	}
	
	public Document convertToDictionaryXML(){
		if(StringUtils.isEmpty(ctrlFilename)){
			return null;
		}
		if(StringUtils.isEmpty(homePath)){
			int p = ctrlFilename.lastIndexOf(File.separator);
			homePath = ctrlFilename.substring(0, p + 1);
		}
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("dic");
		File home = new File(homePath);
		file2Tree(home, root);
		Element scs = (Element) root.selectSingleNode("item[@key='schemas']");
		if(scs != null){
			root.remove(scs);
		}
		return doc;
	}
	
	private void file2Tree(File file,Element parent){
		if(!file.isDirectory()){
			return;
		}
		File[] files = file.listFiles();
		for(File f:files){
			String key = f.getName();
			int index = f.getName().lastIndexOf(".");
			if(index > -1){
				key = f.getName().substring(0, f.getName().lastIndexOf("."));
			}
			Element el = parent.addElement("item").addAttribute("key", key).addAttribute("text", key);
			if(f.isDirectory()){
				el.addAttribute("folder", "true");
			}else{
				System.out.println(f);
				el.addAttribute("text", XMLHelper.getDocument(f).getRootElement().attributeValue("alias",key));
			}
			file2Tree(f, el);
		}
	}
}
